package com.rainy.upload.service;

import com.rainy.upload.config.UploadConfig;
import com.rainy.upload.exception.ExceptionFactory;
import com.rainy.upload.utils.I18nUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class ImgUploadService {

    /**
     * 上传文件
     * @param uploadFile
     * @return
     */
    public String uploadFile(String userName, MultipartFile uploadFile) {
        Date nowTime = new Date();
        SimpleDateFormat year = new SimpleDateFormat("yyyy");
        SimpleDateFormat month = new SimpleDateFormat("MM");
        SimpleDateFormat day = new SimpleDateFormat("dd");

        //图片判断(bmp,jpg,png,tiff,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF)
        if (StringUtils.isEmpty(userName)) {
            throw ExceptionFactory.newInstanceApp(I18nUtils.getCurrentMessage("app.error.user.not-found"));
        }
        Boolean flag = Boolean.FALSE;
        String fileName = uploadFile.getOriginalFilename();
        if (fileName.indexOf(".") < 1 || fileName.lastIndexOf(".") + 1 >= fileName.length()) {
            throw ExceptionFactory.newInstanceApp(I18nUtils.getCurrentMessage("app.error.file.format"));
        }

        String prev = fileName.substring(0, fileName.indexOf("."));
        String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
        String[] defineSuffixs = UploadConfig.getSuffix().split(",");
        for (String defineSuffix : defineSuffixs) {
            if (defineSuffix.equalsIgnoreCase(suffix)) {
                flag = Boolean.TRUE;
                break;
            }
        }

        if (!flag) {
            throw ExceptionFactory.newInstanceApp(I18nUtils.getCurrentMessage("app.error.file.format"));
        }

        String namespace = UploadConfig.getTarget() + "/" + userName + "/" + year.format(nowTime) + "/" + month.format(nowTime) + "/" + day.format(nowTime);
        String filePath = namespace + "/" + prev + "_" + UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;

        //判断文件是否存在
        File tmpFile = new File(filePath);
        File parentFile = tmpFile.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        try {
            FileCopyUtils.copy(uploadFile.getBytes(), tmpFile);
        } catch (IOException e) {
            throw ExceptionFactory.newInstanceApp(e.getMessage());
        }
        return filePath;
    }

}
